<?php
    /**
     * CategoryModel.php
     *
     * Part of m.beetobees
     *
     * For the full copyright and license information, please view the LICENSE
     * file that was distributed with this source code.
     *
     * @author    xiaxianmao <xiaxianmao@cyou-inc.com>
     * @copyright cyou.com
     * @date      2016-12-05
     * @link      
     */

    namespace App\Http\Models;

    use Illuminate\Database\Eloquent\Model;
    use App\Http\Models\CacheModel;

    class CategoryModel extends Model
    {
        protected $connection = 'db_main_slave';

        protected $table = 'wp_sdk_category';

        public $timestamps = false;


        public static function get_all($cateid = 0)
        {
            $cache = CacheModel::get('category');
            if($cache && $ret = json_decode($cache, true))
            {
                return $cateid > 0 && isset($ret[$cateid])  ? $ret[$cateid]['elements']  : $ret;
            }

            $categorys = CategoryModel::where(['status' => 1])
                    ->orderBy('sort', 'DESC')
                    ->get();

            foreach ($categorys as $category) {
                if($category['pid'] == 0 ) {
                    $key = $category['key'];
                    $name = $category['name'];
                    $ret[$key] = isset($ret[$key]) ? $ret[$key] : array();

                    $ret[$key]['key'] = $key;
                    $ret[$key]['name'] = $name;
                } else {
                    $pid = $category['pid'];
                    $id = $category['id'];
                    $name = $category['name'];

                    $ret[$pid] = isset($ret[$pid]) ? $ret[$pid] : array();
                    $ret[$pid]['elements'] = isset($ret[$pid]['elements']) ? $ret[$pid]['elements'] : array();
                    $ret[$pid]['elements'][$id] = array(
                        'key' => $id,
                        'name' => $name
                        ); 
                }
            }
            CacheModel::set('category', json_encode($ret));
            return $cateid > 0 && isset($ret[$cateid])  ? $ret[$cateid]['elements']  : $ret;
        }

    }

    
